﻿using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Max.PH5_2010A.Shopping.Domain.Shared;
using Max.PH5_2010A.Shopping.DTO;
using Max.PH5_2010A.Shopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

namespace Max.PH5_2010A.Shopping.API.Controllers
{
    [Route("order")]
    [ApiController]
    public class OrderController : ControllerBase
    {

        IOrderMasterService _orderService;
        IOrderDetailService _orderDetailService;
        public OrderController(IOrderMasterService orderService, IOrderDetailService orderDetailService)
        {
            _orderService = orderService;
            _orderDetailService = orderDetailService;
        }

        /// <summary>
        /// 添加订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CreateOrder(OrderInputDto dto)
        {
            ResponseResultDto result = new();

            var data = _orderService.CreateOrder(dto);

            if (data.Item1)
            {
                result.Data = data.Item2;
            }
            else
            {
                result.Code = ResponseResultCode.Failed;
                result.Message = data.Item2;
            }

            return Ok(result);
        }


        /// <summary>
        /// 支付宝支付
        /// </summary>
        /// <returns></returns>
        [HttpGet("alipay")]
        public IActionResult Alipay(string orderNo)
        {

            ResponseResultDto dto = new();

            var m = _orderService.Select().Where(x => x.OrderNo.Equals(orderNo)).FirstOrDefault();
            if (m == null)
            {
                dto.Code = ResponseResultCode.Failed;
                dto.Message = "非法请求";
                return Ok(dto);
            }



            //应用私钥
            string privateKey = "MIIEowIBAAKCAQEA2auDwSgWS9cbSq2t4WnF7YKm5pVaEUTMN3cMnRPjkarfH79OtKGVaxAqcvS3xHWfwZBkteKyk15B+u12bIG93+nnPe36A4OUY+UHic+vs9K+pR3EBOa/2cQo8SnoEBylEHiQ5q/GnHICB2fD7aMbRG4Qby+s42MWwy3qAAgipPfI6QMzRoNQTAOhy/ARc1hU5g8DpKuiaHRnoun++t0vz3HUb5DhvUxK1o2GGpkItiSB3QOjkbG3Gwxqxdrk1W5HL+KMyveXtcqg3vl46J4pk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XkPomxMJ+ILx1Tl6y4wZF6d77N6wJ+U1R78zcFgDjEnmSVBO/yH8rAQKBgDIkybqJgTQXUOwVP3ElGbwgG6PIj4gsNsFhIbpqV7ARpxm3L/PCoZqoXGj6vdo71w8dXmzZtwnvZEETsx15vR1X5OC9LKHXILj14/RKJFZ9UVQ7XIvMxEppwoLIV8/hTZPtlA4QhiR7Eco9Ux1B4B1zOrB6xK2LImOfM6J3A8gt";

            //支付公钥
            string alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnCsH1r9TPxFE9mXQv8lo+i/GqfAJvMSRMoFBrtdhFg9P/utVE5FZSyD/Oi+AVYIi0JFClyj1O+hn//MoiIJEhpCKVmsMS4+/QeKk4TgYbkFO6BykNgUqQViy17Yj2Bne/K9duhH4JBWjv9xZGPOvWBa68GBjwjB3o3GGtH1C1RWS0Y8iceVO98dHe773F9y//4xzkqGr7m3IL5v/xVhBOdipkuTfoa862sLGYDQ9dnZJr/rzXNzQRpAE3IJU8uc1z8dbJgC2BP033qlVqCQ66+HVrYlyzbgjaJSX2tE0p2GWltCYqTyaMiaH9OgDAqyqAbTXgKMHFAuo65AjkWJ/ywIDAQAB";
            AlipayConfig alipayConfig = new AlipayConfig();
            alipayConfig.ServerUrl = "https://openapi.alipaydev.com/gateway.do";
            alipayConfig.AppId = "2016092900625246";
            alipayConfig.PrivateKey = privateKey;
            alipayConfig.Format = "json";
            alipayConfig.AlipayPublicKey = alipayPublicKey;
            alipayConfig.Charset = "UTF-8";
            alipayConfig.SignType = "RSA2";
            IAopClient alipayClient = new DefaultAopClient(alipayConfig);
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            //商户订单号
            model.OutTradeNo = orderNo;
            //订单金额
            model.TotalAmount = m.OrderAccount.ToString();
            //主题
            model.Subject = "沙箱测试";
            //产品代码
            model.ProductCode = "FAST_INSTANT_TRADE_PAY";
            request.SetBizModel(model);
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (!response.IsError)
            {
                //Console.WriteLine("调用成功");
                dto.Data = response.Body;
                dto.Message = "调用成功";
            }
            else
            {
                //Console.WriteLine("调用失败");
                dto.Code = ResponseResultCode.Failed;
                dto.Message = "调用失败";
            }

            return Ok(dto);
        }



        /// <summary>
        /// 获取订单状态的枚举值
        /// </summary>
        /// <returns></returns>
        [HttpGet("state")]
        public IActionResult GetOrderEnumState()
        {
            //var fields = typeof(OrderState).GetFields(BindingFlags.Static|BindingFlags.Public);
            //List<object> list = new List<object>();
            //foreach (var item in fields)
            //{
            //    var desc = item.GetCustomAttributes(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute),true);
            //    var m = "";
            //    if (desc != null)
            //    {
            //        m = ((System.ComponentModel.DataAnnotations.DisplayAttribute)desc[0]).Description;

            //    }
            //}

            //System.Type
            //System.Reflection
            //获取这个类或对象的类型
            var t = typeof(OrderState);

            var ns = t.GetEnumNames();

            List<dynamic> list = new List<dynamic>();

            ns.ToList().ForEach(x =>
            {
                //获取这个字段对应的值-----是整形的值
                var value = (int)Enum.Parse(t, x);

                //根据名称去拿到这个字段
                var f = t.GetField(x);

                //获取这个字段的自定义Display的特性
                var da = f.GetCustomAttribute(typeof(System.ComponentModel.DataAnnotations.DisplayAttribute));

                string desc = "";
                if (da != null)
                {
                    desc = ((System.ComponentModel.DataAnnotations.DisplayAttribute)da)?.Description;
                }
                else
                {
                    desc = x;
                }

                list.Add(new { key = desc, value = value.ToString() });
            });

            return Ok(list);
        }

        /// <summary>
        /// 获取这个用户（即会员）的所有的订单数据
        /// </summary>
        /// <param name="date">1等于今天，2等于本周，3等于本月，4等本季，5本年</param>
        /// <returns></returns>
        [HttpGet("list")]
        public IActionResult GetOrderList(string memberId, int state = -1, string date = "5")
        {
            var data = _orderService.Select().Where(x => x.MemberID.ToString().Equals(memberId));

            if (state != -1)
                data = data.Where(x => state == (int)x.OrderState);

            switch (date)
            {
                case "1": //今天
                    data = data.Where(x => x.OrderCreatedTime.Date == System.DateTime.Now.Date);
                    break;
                case "2": //本周
                    //本周(一个范围)  <=今天  ,  >=这周的第一天
                    /*
                     * 1、先拿到今天星期几
                     * 2、再往前推几天
                     * **/
                    int a = (int)System.DateTime.Now.DayOfWeek;
                    if (a == 0) a = 7;//如果是星期天

                    //这是今天之前的日期（往前推，今天之后的日期还没到，不用管）
                    var startData = System.DateTime.Now.AddDays(-(a - 1));

                    data = data.Where(x => x.OrderCreatedTime.Date >= startData.Date && x.OrderCreatedTime.Date <= System.DateTime.Now.Date);

                    break;
                case "3"://本月
                    data = data.Where(x => x.OrderCreatedTime.Month == System.DateTime.Now.Month);
                    break;
                case "4": //本季度
                    var season2 = this.GetSeason2(System.DateTime.Now.Month);
                    int start = Convert.ToInt32(season2.Item1);
                    int end = Convert.ToInt32(season2.Item2);
                    data = data.Where(x => x.OrderCreatedTime.Month >= start
                                        && x.OrderCreatedTime.Month <= end);
                    break;
                case "5":
                default:
                    data = data.Where(x => x.OrderCreatedTime.Year == System.DateTime.Now.Year);
                    break;
            }


            //var q = from a in data
            //        select new
            //        {
            //            OrderCreatedTime = a.OrderCreatedTime.ToString("yyyyMMdd")
            //        };

            return Ok(data);
        }

        private string[] GetSeason(int month)
        {
            List<string[]> s = new List<string[]>();
            s.Add(new string[] { "1", "2", "3" });
            s.Add(new string[] { "4", "5", "6" });
            s.Add(new string[] { "7", "8", "9" });
            s.Add(new string[] { "10", "11", "12" });

            //向上取整，得到这个月份所属的季度
            int a = (int)Math.Ceiling(month / 3.0);

            return s[a - 1];
        }

        private (int, int) GetSeason2(int month)
        {
            var a = month % 3;

            a = a == 0 ? 3 : a;

            //这个季度中，最少的月份
            var min = month - (a - 1);

            return (min, month);
        }

    }
}
